package cn.itsource.pethome.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * springmvc的拦截器
 *
 */
//往spring容器里面注册bean
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //做什么事情
        //1.获取请求头
        String token = request.getHeader("token");
        //2.校验token
        if(!StringUtils.isEmpty(token)){//不为null才会进来
            //3.根据token获取redis的值
            Object userinfo = redisTemplate.opsForValue().get(token);
            if(userinfo != null){
                //3.2拿不到 刷新token过期时间，放行
                redisTemplate.opsForValue().set(token,userinfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //2.1如果获取不到值返回错误信息
        //3.1拿不到 登录失效返回错误信息
        response.setCharacterEncoding("UTF-8");//如果返回有中文就必须设置 防止乱码
        response.setContentType("application/json;charset=utf-8");//设置返回响应的格式
        PrintWriter writer = response.getWriter();//向外部写数据
        writer.print("{\"success\":false,\"msg\":\"noLogin\"}");//json数据格式
        writer.flush();
        writer.close();
        return false;
        //疑问  这里返回false  前端根本就不知道你通过还是没有通过   没有办法去跳转的登录页面
    }
}